import axios from './axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

export interface LoginParams {
  user: string;
  pwd: string;
}

export interface LoginSuccessData {
  token: string;
  user: {
    uid: number;
    user: string;
    level: string;
    is_active: string;
    name: string;
    mobile: string;
    email: string;
    id_card: string;
    unit: string;
    user_perm: string;
    expires_in: number;
  };
}

export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
}

export const login = async (params: LoginParams): Promise<ApiResponse<LoginSuccessData>> => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.user_operate.login`,
      params
    );
    const data = response.data;
    
    // 适配后端返回的数据结构
    return {
      code: data.code, // 后端返回200表示成功，400表示失败
      message: data.msg || data.message || '登录失败',
      data: data.code === 200 && data.token && data.user ? { 
        token: data.token, 
        user: data.user 
      } : undefined
    };
  } catch (error) {
    console.error('登录失败:', error);
    throw new Error('登录失败');
  }
}; 